<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Validator;
use App\Http\Constant;
use Illuminate\Support\Facades\DB;
use App\Helpers\ValidatorResponse;
use App\Helpers\SuccessResponse;
use App\Http\Model\RbacUser;
use Ixudra\Curl\Facades\Curl;

class RbacUserController extends Controller{

	public function add(Request $request){
		$validator = Validator::make($request->all(), [
			'role_id' => 'required|integer|min:1',
			'name' => 'required|string',
			'email' => 'required|email',
		]);
		if($validator->fails()){
			return ValidatorResponse::handler($validator->errors());
		}else{
			$rbac_user_model = new RbacUser();
			try{
				$new_password = substr(str_shuffle('ABCDEFGHIJKLMNPQRSTUVWXYZabcdefghijkmlnpqrstuvwxyz0123456789'), -12);
				$user_id = $rbac_user_model->createUser($request, $new_password);
				// if(1 > $user_id){
				// 	throw new \Exception('System error.', Constant::EC_SYSTEM_ERROR);
				// }
			}catch(\Exception $e){
				return SuccessResponse::handler('['.$e->getCode().'] '.$e->getMessage());
			}
			$user = [
				'id' => $user_id,
				'role_id' => $request->input('role_id'),
				'name' => $request->input('name'),
				'email' => $request->input('email'),
			];
			$send_mail_url = env('COMMUNICATION_URL', false);
			$send_mail_url .= '/email/send';
			$response = Curl::to($send_mail_url)
				->withData([
					'email' => $user['email'],
					'subject' => 'Account Default Password',
					'body' => '',
					'template' => 'code',
					'data' => json_encode([
						'user' => $user['name'],
						'code' => $new_password
					]),
				])
	        	->post();
	        $rtn_data = ['user' => $user, 'response' => $response];
			return SuccessResponse::handler($rtn_data);
		}
	}

	public function open(Request $request){
		$validator = Validator::make($request->all(), [
			'id' => 'required|integer|min:1',
		]);
		if($validator->fails()){
			return ValidatorResponse::handler($validator->errors());
		}else{
			$rbac_user_model = new RbacUser();
			try{
				$rbac_user_model->updateStatus($request, Constant::TFEX_USERS_STATUS_OPEN);
			}catch(\Exception $e){
				return SuccessResponse::handler('['.$e->getCode().'] '.$e->getMessage());
			}
			return SuccessResponse::handler(['id' => $request->input('id')]);
		}
	}

	public function close(Request $request){
		$validator = Validator::make($request->all(), [
			'id' => 'required|integer|min:1',
		]);
		if($validator->fails()){
			return ValidatorResponse::handler($validator->errors());
		}else{
			$rbac_user_model = new RbacUser();
			try{
				$rbac_user_model->updateStatus($request, Constant::TFEX_USERS_STATUS_CLOSE);
			}catch(\Exception $e){
				return SuccessResponse::handler('['.$e->getCode().'] '.$e->getMessage());
			}
			return SuccessResponse::handler(['id' => $request->input('id')]);
		}
	}

	public function delete(Request $request){
		$validator = Validator::make($request->all(), [
			'id' => 'required|integer|min:1',
		]);
		if($validator->fails()){
			return ValidatorResponse::handler($validator->errors());
		}else{
			$rbac_user_model = new RbacUser();
			try{
				$rbac_user_model->updateStatus($request, Constant::TFEX_USERS_STATUS_DELETE);
			}catch(\Exception $e){
				return SuccessResponse::handler('['.$e->getCode().'] '.$e->getMessage());
			}
			return SuccessResponse::handler(['id' => $request->input('id')]);
		}
	}

	public function listUser(Request $request){
		$is_page = intval($request->input('is_page')) == 1 ? 1 : 0;
		$show_page = intval($request->input('show_page')) == 1 ? 1 : 0;
		$current_page = intval($request->input('current_page'));
		$current_page = $current_page > 1 ? $current_page : 1;
		$page_count = intval($request['page_count']);
		$page_count = $page_count > 0 ? $page_count : 20;

		$user_status = json_decode($request->input('user_status'), true);
		if(0 == count($user_status)){
			$user_status = [
				Constant::TFEX_USERS_STATUS_OPEN,
				Constant::TFEX_USERS_STATUS_CLOSE,
			];
		}else{
			$user_status = array_values($user_status);
		}
		$keywords = trim(strval($request->input('keywords')));
		$order_by = json_decode($request->input('order_by'), true);
		if(0 != count($order_by)){
			$order_by_arr = array();
			foreach ($order_by as $key => $value) {
				if($value == 'desc' || $value == 'asc'){
					array_push($order_by_arr, $key.' '.$value);
				}else{
					continue;
				}
			}
			$order_by = implode(',', $order_by_arr);
		}else{
			$order_by = 'id desc';
		}

		if($is_page){
			$data_sql = 'select * from users';
			if($user_status || strlen($keywords)){
				$data_sql .= ' where 1=1';
				if($user_status){
					$data_sql .= ' and status in ('.implode(',', $user_status).')';
				}
				if(strlen($keywords)){
					$data_sql .= ' and ( name like "%'.$keywords.'%" or email like "%'.$keywords.'%" )';
				}
			}
			$data_sql .= ' order by '.$order_by;
			$limit_start = ($current_page - 1) * $page_count;
			$data_sql .= ' limit '.$limit_start.','.$page_count;
			$user_data = DB::select($data_sql);
			$page_info = array(
				'total' => count($user_data),
				'total_page' => 1,
			);
			if($show_page){
				$count_sql = 'select count(*) as total from users';
				if($user_status || strlen($keywords)){
					$count_sql .= ' where 1=1';
					if($user_status){
						$count_sql .= ' and status in ('.implode(',', $user_status).')';
					}
					if(strlen($keywords)){
						$count_sql .= ' and ( name like "%'.$keywords.'%" or email like "%'.$keywords.'%" )';
					}
				}
				$user_count = DB::select($count_sql);
				$user_count = json_decode(json_encode($user_count), true);
				$page_info = array(
					'total' => $user_count[0]['total'],
					'total_page' => ceil($user_count[0]['total'] / $page_count),
				);
			}
		}else{
			$data_sql = 'select * from users';
			if($user_status || strlen($keywords)){
				$data_sql .= ' where 1=1';
				if($user_status){
					$data_sql .= ' and status in ('.implode(',', $user_status).')';
				}
				if(strlen($keywords)){
					$data_sql .= ' and ( name like "%'.$keywords.'%" or email like "%'.$keywords.'%" )';
				}
			}
			$data_sql .= ' order by '.$order_by;
			$data_sql .= ' limit 0,999';
			$user_data = DB::select($data_sql);
			$page_info = array(
				'total' => count($user_data),
				'total_page' => 1,
			);
		}
		$user_data = json_decode(json_encode($user_data), true);
		$roles = DB::select('select * from rbac_role where status != 3');
		$roles = json_decode(json_encode($roles), true);
		$roles_key_value = [];
		foreach ($roles as $value) {
			$roles_key_value[$value['id']] = $value['role_name'];
		}
		foreach ($user_data as &$user) {
			unset($user['password']);
			$user['role_name'] = $roles_key_value[$user['role_id']];
		}
		$rtn_data = array(
			'where' => array(
				'is_page' => $is_page,
				'show_page' => $show_page,
				'current_page' => $current_page,
				'page_count' => $page_count,
				'order_by' => $order_by,
				'user_status' => $user_status,
				'keywords' => $keywords,
			),
			'data' => $user_data,
		);
		if($show_page){
			$rtn_data['show_page'] = $page_info;
		}
		return SuccessResponse::handler($rtn_data);
	}

	public function initPassword(Request $request){
        $validator = Validator::make($request->all(), [
			'id' => 'required|integer|min:1',
		]);
		if($validator->fails()){
			return ValidatorResponse::handler($validator->errors());
		}else{
			$rbac_user_model = new RbacUser();
			$user = $rbac_user_model->where('id', '=', $request->input('id'))->get()->toArray();
			if(0 == count($user)){
				return SuccessResponse::handler('['.Constant::EC_RBAC_USER_NOT_EXIST.'] Rbac user not exists.');
			}else{
				$new_password = substr(str_shuffle('ABCDEFGHIJKLMNPQRSTUVWXYZabcdefghijkmlnpqrstuvwxyz0123456789'), -12);
				try{
					$rbac_user_model->where('id', '=', $request->input('id'))->update([
						'password' => $rbac_user_model->_createRbacUserPassword($new_password),
						'default_password' => Constant::TFEX_USERS_DEFAULT_PASSWORD,
					]);
				}catch(\Exception $e){
					return SuccessResponse::handler('['.$e->getCode().'] '.$e->getMessage());
				}
				$send_mail_url = env('COMMUNICATION_URL', false);
				$send_mail_url .= '/email/send';
				$response = Curl::to($send_mail_url)
					->withData([
						'email' => $user[0]['email'],
						'subject' => 'Password reset notification',
						'body' => '',
						'template' => 'code',
						'data' => json_encode([
							'user' => $user[0]['name'],
							'code' => $new_password
						]),
					])
		        	->post();
				return SuccessResponse::handler(['id'=>$request->input('id'), 'response' => $response]);
			}
		}
	}

	public function modifyPassword(Request $request){
		$validator = Validator::make($request->all(), [
			'id' => 'required|integer|min:1',
			'password' => 'required|string|min:6|max:18|confirmed',
		]);
		if($validator->fails()){
			return ValidatorResponse::handler($validator->errors());
		}else{
			$rbac_user_model = new RbacUser();
			$user = $rbac_user_model->where('id', '=', $request->input('id'))->get()->toArray();
			if(0 == count($user)){
				return SuccessResponse::handler('['.Constant::EC_RBAC_USER_NOT_EXIST.'] Rbac user not exists.');
			}else{
				if($user[0]['default_password'] == Constant::TFEX_USERS_DEFAULT_PASSWORD){
					try{
						$rbac_user_model->where('id', '=', $request->input('id'))->update([
							'password' => $rbac_user_model->_createRbacUserPassword($request->input('password')),
							'default_password' => Constant::TFEX_USERS_MODIFIED_PASSWORD,
						]);
					}catch(\Exception $e){
						return SuccessResponse::handler('['.$e->getCode().'] '.$e->getMessage());
					}
					$send_mail_url = env('COMMUNICATION_URL', false);
					$send_mail_url .= '/email/send';
					$response = Curl::to($send_mail_url)
						->withData([
							'email' => $user[0]['email'],
							'subject' => 'Password reset notification',
							'body' => '',
							'template' => 'code',
							'data' => json_encode([
								'user' => $user[0]['name'],
								'code' => $request->input('password')
							]),
						])
			        	->post();
					return SuccessResponse::handler(['id'=>$request->input('id'), 'response' => $response]);
				}else{
					return SuccessResponse::handler('['.Constant::EC_RBAC_USER_CAN_NOT_MODIFY_PASSWORD.'] Rbac user can not modify password.');
				}
			}
		}
	}

	public function saveProfile(Request $request){
		$validator = Validator::make($request->all(), [
			'id' => 'required|integer|min:1',
			'name' => 'required|string',
			'role_id' => 'integer|min:1',
		]);	
		if($validator->fails()){
			return ValidatorResponse::handler($validator->errors());
		}else{
			$rbac_user_model = new RbacUser();
			$update_data = [];
			if($request->input('name')){
				$update_data['name'] = $request->input('name');
			}
			if($request->input('role_id')){
				$update_data['role_id'] = $request->input('role_id');
			}
			try{
				$rbac_user_model->where('id', '=', $request->input('id'))->update($update_data);
			}catch(\Exception $e){
				return SuccessResponse::handler('['.$e->getCode().'] '.$e->getMessage());
			}
			$rtn = [
				'id' => $request->input('id'),
				'data' => [
					'name' => $request->input('name'),
				],
			];
			return SuccessResponse::handler($rtn);
		}
	}

	public function detail(Request $request){
		$validator = Validator::make(['id' =>$request->input('id')], [
			'id' => 'required|integer|min:1',
		]);
		if($validator->fails()){
			return ValidatorResponse::handler($validator->errors());
		}else{
			$rbac_user_model = new RbacUser();
			try{
				$user = $rbac_user_model->where('id', '=', $request->input('id'))->get()->toArray();
			}catch(\Exception $e){
				return SuccessResponse::handler('['.$e->getCode.'] '.$e->getMessage());
			}
			unset($user[0]['password']);
			unset($user[0]['remember_token']);
			return SuccessResponse::handler($user);
		}
	}
}